package com.quartet.modules.terminal.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.quartet.api.ApiResult;
import com.quartet.api.PageResult;
import com.quartet.modules.customer.entity.TCustomerInfo;
import com.quartet.modules.customer.service.TCustomerInfoService;
import com.quartet.modules.order.entity.TOrder;
import com.quartet.modules.order.service.TOrderService;
import com.quartet.modules.service.service.TServiceInfoService;
import com.quartet.modules.stock.entity.TFlowCardStock;
import com.quartet.modules.stock.entity.TTerminalStock;
import com.quartet.modules.stock.service.TFlowCardStockService;
import com.quartet.modules.stock.service.TTerminalStockService;
import com.quartet.modules.terminal.dto.TTerminalInfoRequestAddDto;
import com.quartet.modules.terminal.dto.TTerminalInfoRequestQueryDto;
import com.quartet.modules.terminal.dto.TTerminalInfoResponseDto;
import com.quartet.modules.terminal.entity.TTerminalInfo;
import com.quartet.modules.terminal.service.TFlowCardInfoService;
import com.quartet.modules.terminal.service.TTerminalInfoService;
import com.quartet.utils.constant.MapServerConstant;
import com.quartet.utils.enums.ActiveStatusEnum;
import com.quartet.utils.enums.InventoryStatusEnum;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 终端信息表(TTerminalInfo)表控制层
 *
 * @author makejava
 * @since 2021-06-14 09:20:38
 */
@RestController
@RequestMapping("tTerminalInfo")
@Slf4j
@Api(tags = "业务：终端管理")
public class TTerminalInfoController {
    /**
     * 服务对象
     */
    @Resource
    private TTerminalInfoService tTerminalInfoService;
    /**
     * 服务对象
     */
    @Resource
    private TCustomerInfoService tCustomerInfoService;
    /**
     * 服务对象
     */
    @Resource
    private TFlowCardInfoService tFlowCardInfoService;
    /**
     * 服务对象
     */
    @Resource
    private TOrderService tOrderService;
    /**
     * 服务对象
     */
    @Resource
    private TTerminalStockService tTerminalStockService;
    /**
     * 服务对象
     */
    @Resource
    private TServiceInfoService tServiceInfoService;
    /**
     * 服务对象
     */
    @Resource
    private TFlowCardStockService tFlowCardStockService;

    /**
     * 分页查询所有数据
     *
     * @param tTerminalInfoRequestQueryDto 查询实体
     * @return 所有数据
     */
    @PostMapping("/selectTerminalPage")
    public ApiResult<PageResult<TTerminalInfoResponseDto>> selectTerminalPage(@RequestBody TTerminalInfoRequestQueryDto tTerminalInfoRequestQueryDto) {

        QueryWrapper<TOrder> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.lambda().eq(TOrder::getCustomerCode, tTerminalInfoRequestQueryDto.getCustomerCodeList());
        List<String> orderCodeList = tOrderService.list(queryWrapper1).stream().map(tOrder -> tOrder.getOrderCode()).collect(Collectors.toList());


        log.info("---------selectTerminalPage begin, tTerminalInfoRequestQueryDto is {}----------", tTerminalInfoRequestQueryDto);
        IPage<TTerminalInfo> page = new Page<>(tTerminalInfoRequestQueryDto.getCurrent(), tTerminalInfoRequestQueryDto.getLimit());
        QueryWrapper<TTerminalInfo> queryWrapper = new QueryWrapper<>();
        if (!CollectionUtils.isEmpty(tTerminalInfoRequestQueryDto.getCustomerCodeList())) {
            queryWrapper.lambda().ge(TTerminalInfo::getOrderCode, orderCodeList);
        }
        if (StringUtils.isNotBlank(tTerminalInfoRequestQueryDto.getTerminalCode())) {
            queryWrapper.lambda().like(TTerminalInfo::getTerminalCode, tTerminalInfoRequestQueryDto.getTerminalCode());
        }
        if (StringUtils.isNotBlank(tTerminalInfoRequestQueryDto.getFlowCardNumber())) {
            queryWrapper.lambda().like(TTerminalInfo::getFlowCardNumber, tTerminalInfoRequestQueryDto.getFlowCardNumber());
        }
        if (StringUtils.isNotBlank(tTerminalInfoRequestQueryDto.getAllocationStatus())) {
            queryWrapper.lambda().eq(TTerminalInfo::getAllocationStatus, tTerminalInfoRequestQueryDto.getAllocationStatus());
        }
        if (StringUtils.isNotBlank(tTerminalInfoRequestQueryDto.getField())) {
            queryWrapper.orderBy(true, tTerminalInfoRequestQueryDto.isAsc(), tTerminalInfoRequestQueryDto.getField());
        } else {
            queryWrapper.orderBy(true, tTerminalInfoRequestQueryDto.isAsc(), MapServerConstant.CREATE_TIME);
        }
        IPage<TTerminalInfo> dbResult = tTerminalInfoService.page(page, queryWrapper);
        PageResult<TTerminalInfoResponseDto> pageResult = new PageResult();
        List<TTerminalInfoResponseDto> terminalInfoResponseDtoList = dbResult.getRecords().stream().map(tTerminalInfo -> {
            TTerminalInfoResponseDto terminalInfoResponseDto = getTTerminalInfoResponseDto(tTerminalInfo);
//            tOrderResponseDto.setApplicationTypeLabel(dictDetailServicePs.getLabelByValueByCode(tOrderResponseDto.getApplicationType()));
            return terminalInfoResponseDto;
        }).collect(Collectors.toList());
        pageResult.setTotal(dbResult.getTotal());
        pageResult.setData(terminalInfoResponseDtoList);
        log.info("---------selectTerminalPage end, data is {}----------", pageResult);
        return ApiResult.ok(pageResult);
    }

    /**
     * 设置客户名称信息
     *
     * @param tTerminalInfo
     * @return
     */
    private TTerminalInfoResponseDto getTTerminalInfoResponseDto(TTerminalInfo tTerminalInfo) {
        TTerminalInfoResponseDto terminalInfoResponseDto = BeanUtil.copyProperties(tTerminalInfo, TTerminalInfoResponseDto.class);

        if (StringUtils.isBlank(tTerminalInfo.getOrderCode())) {
            return terminalInfoResponseDto;
        }
        TOrder tOrder = tOrderService.getOne(new QueryWrapper<TOrder>().lambda().eq(TOrder::getOrderCode, tTerminalInfo.getOrderCode()));
        if (ObjectUtils.isEmpty(tOrder)) {
            return terminalInfoResponseDto;
        }
        if (StringUtils.isNotBlank(tOrder.getCustomerCode())) {
            QueryWrapper<TCustomerInfo> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.lambda().eq(TCustomerInfo::getCustomerCode, tOrder.getCustomerCode());
            TCustomerInfo tCustomerInfo = tCustomerInfoService.getOne(queryWrapper1);
            if (!ObjectUtils.isEmpty(tCustomerInfo)) {
                terminalInfoResponseDto.setCustomerName(tCustomerInfo.getCustomerName());
            }
        }
        return terminalInfoResponseDto;
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/getTerminalById")
    public ApiResult<TTerminalInfoResponseDto> getTerminalById(@RequestParam("id") Integer id) {
        TTerminalInfo tTerminalInfo = tTerminalInfoService.getById(id);
        if (ObjectUtils.isEmpty(tTerminalInfo)) {
            return null;
        }
        TTerminalInfoResponseDto terminalInfoResponseDto = getTTerminalInfoResponseDto(tTerminalInfo);
        return ApiResult.ok(terminalInfoResponseDto);
    }

    /**
     * 新增数据
     *
     * @param tTerminalInfoRequestAddDto 实体对象
     * @return 新增结果
     */
    @PostMapping("/addTerminal")
    public ApiResult addTerminal(@RequestBody TTerminalInfoRequestAddDto tTerminalInfoRequestAddDto) {
        TTerminalInfo tTerminalInfo = BeanUtil.copyProperties(tTerminalInfoRequestAddDto, TTerminalInfo.class);
        return ApiResult.ok(this.tTerminalInfoService.save(tTerminalInfo));
    }

    /**
     * 修改数据
     *
     * @param tTerminalInfoRequestAddDto 实体对象
     * @return 修改结果
     */
    @PutMapping("/updateTerminal")
    public ApiResult updateTerminal(@RequestBody TTerminalInfoRequestAddDto tTerminalInfoRequestAddDto) {
        TTerminalInfo tTerminalInfo = BeanUtil.copyProperties(tTerminalInfoRequestAddDto, TTerminalInfo.class);
        return ApiResult.ok(this.tTerminalInfoService.updateById(tTerminalInfo));
    }

    /**
     * 删除数据
     *
     * @param id 主键结合
     * @return 删除结果
     */
    @DeleteMapping("/deleteTerminal")
    public ApiResult deleteTerminal(@RequestParam("id") Integer id) {
        return ApiResult.ok(this.tTerminalInfoService.removeById(id));
    }

//    /**
//     * 终端分配
//     *
//     * @param id
//     * @param customerCode
//     * @return
//     */
//    @PostMapping("/allocationTerminal")
//    public ApiResult allocationTerminal(@RequestParam("id") Integer id, @RequestParam("customerCode") String customerCode) {
//        TTerminalInfo tTerminalInfo = tTerminalInfoService.getById(id);
//        if (StringUtils.isNotBlank(tTerminalInfo.getCustomerCode())) {
//            throw new MapServerException(ResultErrorEnum.BMKPM001);
//        }
//        //更改终端状态并关联客户
//        UpdateWrapper<TTerminalInfo> updateWrapper = new UpdateWrapper<>();
//        updateWrapper.lambda().eq(TTerminalInfo::getId, id)
//                .set(TTerminalInfo::getAllocationStatus, TerminalAllocationEnum.ALLOCATED.getValue())
//                .set(TTerminalInfo::getCustomerCode, customerCode);
//        this.tTerminalInfoService.update(updateWrapper);
//        //给客户的关联终端个数加一
//        tCustomerInfoService.updateCustomerAssignedTerminalsNum(customerCode);
//        return ApiResult.ok();
//    }

//    /**
//     * 绑定流量卡
//     *
//     * @param id
//     * @param flowCardNumber
//     * @return
//     */
//    @PostMapping("/bindingFlowCard")
//    public ApiResult bindingFlowCard(@RequestParam("id") Integer id, @RequestParam("flowCardNumber") String flowCardNumber) {
//        TTerminalInfo tTerminalInfo = tTerminalInfoService.getById(id);
//        if (StringUtils.isNotBlank(tTerminalInfo.getFlowCardNumber())) {
//            throw new MapServerException(ResultErrorEnum.BMKPM002);
//        }
//        //更改终端信息
//        UpdateWrapper<TTerminalInfo> updateWrapper = new UpdateWrapper<>();
//        updateWrapper.lambda().eq(TTerminalInfo::getId, id)
//                .set(TTerminalInfo::getFlowCardNumber, flowCardNumber);
//        this.tTerminalInfoService.update(updateWrapper);
//        //更新流量卡状态
//        UpdateWrapper<TFlowCardInfo> updateWrapper1 = new UpdateWrapper<>();
//        updateWrapper1.lambda().eq(TFlowCardInfo::getFlowCardNumber, flowCardNumber).set(TFlowCardInfo::getInventoryStatus, FlowCardInventoryStatusEnum.ALLOCATED.getValue());
//        tFlowCardInfoService.update(updateWrapper1);
//        return ApiResult.ok();
//    }

    /**
     * 终端下拉列表
     *
     * @return
     */
    @GetMapping("/queryCustomerCodeByTerminalCode")
    public ApiResult<Map<String, Object>> queryCustomerCodeByTerminalCode(@RequestParam("terminalCode") String terminalCode,@RequestParam("flowCardNumber") String flowCardNumber) {
        log.info("queryCustomerCodeByTerminalCode begin,param is {} and {}",terminalCode,flowCardNumber);
        Map<String, Object> map = new HashedMap<>();
        QueryWrapper<TTerminalStock> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TTerminalStock::getTerminalCode, terminalCode);
        TTerminalStock tTerminalStock = tTerminalStockService.getOne(queryWrapper);

        QueryWrapper<TFlowCardStock> queryWrapper1=new QueryWrapper<>();
        queryWrapper1.lambda().eq(TFlowCardStock::getFlowCardNumber,flowCardNumber);
        TFlowCardStock tFlowCardStock = tFlowCardStockService.getOne(queryWrapper1);

        if (ObjectUtils.isEmpty(tTerminalStock)||ObjectUtils.isEmpty(tFlowCardStock)){
            map.put("isValid", false);
        }else {
            map.put("isValid", true);
            map.put("customerCode","00000000");
            //修改库存状态为待出库
            UpdateWrapper<TTerminalStock> updateWrapper1 = new UpdateWrapper<>();
            updateWrapper1.lambda().eq(TTerminalStock::getTerminalCode, terminalCode)
                    .set(TTerminalStock::getOrderCode, "")
                    .set(TTerminalStock::getDeliveryTime, null)
                    .set(TTerminalStock::getInventoryStatus, InventoryStatusEnum.TOBEALLOCATED.getValue());
            tTerminalStockService.update(updateWrapper1);

            UpdateWrapper<TFlowCardStock> updateWrapper=new UpdateWrapper<>();
            updateWrapper.lambda().eq(TFlowCardStock::getFlowCardNumber, flowCardNumber)
                    .set(TFlowCardStock::getDeliveryTime, null)
                    .set(TFlowCardStock::getInventoryStatus, ActiveStatusEnum.TOBEALLOCATED.getValue());
            tFlowCardStockService.update(updateWrapper);
            log.info("update TTerminalStock and TFlowCardStock success");
        }
        return ApiResult.ok(map);
    }

}
